﻿using System;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;


namespace CourseScheduledTaskAgent
{

    public class ScheduledAgent : ScheduledTaskAgent
    {
        public static string PERIODICTASKNAME = "PeriodicTaskTest";



        /// <remarks>
        /// ScheduledAgent 构造函数，初始化 UnhandledException 处理程序
        /// </remarks>
        static ScheduledAgent()
        {
            // 订阅托管的异常处理程序
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        /// 出现未处理的异常时执行的代码
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // 出现未处理的异常；强行进入调试器
                Debugger.Break();
            }
        }

        /// <summary>
        /// 运行计划任务的代理
        /// </summary>
        /// <param name="task">
        /// 调用的任务
        /// </param>
        /// <remarks>
        /// 调用定期或资源密集型任务时调用此方法
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO:  添加用于在后台执行任务的代码
            //TODO: Add code to perform your task in background

            // Launch a toast to show that the agent is running.
            // The toast will not be shown if the foreground application is running.

            //ShellToast toast = new ShellToast();

            //toast.Content = "掌控校园推送测试";
            //toast.Title = "掌控校园";
            //toast.Show();


            TimeSpan t1 = new TimeSpan(new DateTime(2014,9,1).Ticks);
            TimeSpan t2 = new TimeSpan(DateTime.Now.Ticks);

            TimeSpan offset = t2.Subtract(t1);//计算天数之差

            int weekNumber = offset.Days/7;//计算周数

            string dataFromIsoStore =
                Convert.ToString(IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + weekNumber.ToString()]);

            WeeklyCourses weeklyCourses = new WeeklyCourses();
            weeklyCourses = JsonConvert.DeserializeObject<WeeklyCourses>(dataFromIsoStore);
            int dayofweek = ((int)DateTime.Now.DayOfWeek - 1 + 7) % 7;
            DailyCourses dailyCourses = weeklyCourses.WeeklyCoursesCollention[dayofweek];


            bool latestCourse = true;
            ShellTile TileToFind = ShellTile.ActiveTiles.First();
            IconicTileData data = new IconicTileData();

            data.Title = "掌控校园";
            data.Count = 0;
            data.IconImage = new Uri("/toolargemiddle.png", UriKind.Relative);
            data.SmallIconImage = new Uri("/toolargesmall.png", UriKind.Relative);
            data.WideContent1 = "";
            data.WideContent2 = "";
            data.WideContent3 = "";


            int count = 0;
            for (int i = 0; i < dailyCourses.DailyCoursesCollection.Count; i++)
            {
                Course course = dailyCourses.DailyCoursesCollection[i];
                if (course.CourseName != "")
                {
                    if (DateTime.Now < course.StartTime.AddMinutes(20)) //保证在上课20分钟内不会更新磁贴
                    {
                        count++;
                        if (latestCourse)
                        {
                            data.IconImage = new Uri("/toolargemiddle.png", UriKind.Relative);
                            data.SmallIconImage = new Uri("/toolargesmall.png", UriKind.Relative);
                            data.WideContent1 = course.CourseName;
                            data.WideContent2 = "时间：" + course.StartTime.ToShortTimeString() + "--" +
                                                course.EndTime.ToShortTimeString();
                            data.WideContent3 = "地点：" + course.Classroom;
                            latestCourse = false;
                        }

                    }

                }

            }

            data.Count = count;
            TileToFind.Update(data);

            // If debugging is enabled, launch the agent again in one minute.
#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif

            // Call NotifyComplete to let the system know the agent is done working.
            NotifyComplete();
        }
    }
}